﻿namespace BEGDC.CC.ExcelTool
{
    #region Using Directives

    using System;
    using System.Configuration;
    using System.IO;
    using System.Web;
    using System.Web.UI;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using Excel;
    using Utility.ExceptionManagement;

    #endregion

    public class ExportEZVForm : ICCExcelExport
    {
        private readonly ExcelExportCommom excelExport = new ExcelExportCommom();

        private readonly string folder = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ExportPath"]);
        private readonly string templateName = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["EZVisitTemplate"]);

        private EZVisitApplicationTableEntity app;
        private int appId;

        #region ICCExcelExport Members

        public void Export(Page page, int id)
        {
            this.appId = id;

            this.app = EZVisitApplicationManager.SelectByKeys(this.appId);

            if (this.app == null)
            {
                return;
            }

            string fileName = this.Export2Excel();

            this.excelExport.Export2Client(page, fileName, "EZVisitForm.xls");
        }

        #endregion

        private string Export2Excel()
        {
            try
            {
                this.excelExport.Open(this.templateName);

                this.GenerateAppInfo();

                this.GenerateContractInfo();

                this.GenerateVisitInfo();

                this.GenerateCustomerInfo();

                this.GenerateAttendeesInfo();

                string fileName = Path.Combine(this.folder, string.Format("{0}-{1}-EZVisitForm.xls", this.app.AppNo, DateTime.Now.Ticks));

                this.excelExport.ExportAs(fileName);

                return fileName;
            }
            catch (Exception ex)
            {
                var exp = new GDCException("export_0001", ex.Message, ex.InnerException);
                throw exp;
            }
            finally
            {
                this.excelExport.Close();
            }
        }

        private void GenerateContractInfo()
        {
            this.SetRange("ContractInfo1", this.app.IsInSalesContract.Value ? "YES" : "NO");

            if (this.app.IsInSalesContract.Value)
            {
                var range = this.GetRange("Contracts");

                var contracts = EZVisitContractItemManager.SelectByCondition("IsEnabled = 1 and AppID=" + this.appId);
                int rowCount = 2;
                while (contracts.Count > rowCount)
                {
                    var r = this.GetRow(range.Cells[2, 1], range.Cells[2, 6]);
                    r.Copy(Type.Missing);
                    r.Insert(XlInsertShiftDirection.xlShiftDown, false);
                    rowCount++;
                }

                int i = 1;

                foreach (EZVisitContractItemTableEntity contract in contracts)
                {
                    this.SetRange(range.Cells[i, 1], contract.ContractNo);
                    this.SetRange(range.Cells[i, 3], contract.EstimatedTotalCost);

                    i++;
                }

                string IsInProducstSold = "YES";
                if (this.app.IsInProducstSold.Value == 0)
                    IsInProducstSold = "NO";
                else if (this.app.IsInProducstSold.Value == 1)
                    IsInProducstSold = "YES";
                else
                    IsInProducstSold = "OTHERS";
                this.SetRange("ContractInfo4", IsInProducstSold);
                this.SetRange("ContractInfo5", this.app.ProducstSold);
            }
            else
            {
                this.SetRange("ContractInfo3", this.app.CostCenter);
            }

            string totalCost = string.Format("¥{0} / {1}(Exchange Rate 汇率) = €{2}", this.app.TotalCost, this.app.ExchangeRate, this.app.TotalCostEUR);

            this.SetRange("ContractInfo2", totalCost);
        }

        private void GenerateVisitInfo()
        {
            string info = string.Format("From {0:MM/dd/yyyy} To {1:MM/dd/yyyy}", this.app.RequestedDateFrom, this.app.RequestedDateTo);

            this.SetRange("VisitInfo1", info);
            this.SetRange("VisitInfo2", this.app.IsDomestic.Value ? this.app.DomesticDesc : this.app.OverseaDesc);
            this.SetRange("VisitInfo3", this.app.OtherSite);
            this.SetRange("VisitInfo4", this.app.ReasonOfLocation);
            this.SetRange("VisitInfo5", this.app.IsNeedGift.Value ? "YES" : "NO");

            if (this.app.IsNeedGift.Value)
            {
                this.SetRange("VisitInfo6", this.app.GiftDesc);

                info = string.Format("€{0}(Unit Price 单价) *{1}(Quantity 数量) ＝ €{2} (Total 总金额) ", this.app.GiftUnitPrice, this.app.GiftAmount, this.app.GiftTotalValue);
                this.SetRange("VisitInfo7", info);
            }

            this.SetRange("VisitInfo8", this.app.VisitCity);
        }

        private void GenerateCustomerInfo()
        {
            this.SetRange("CustomerInfo1", this.app.Company);
            this.SetRange("CustomerInfo2", this.app.IsFCPA.Value ? "YES" : "NO");
            this.SetRange("CustomerInfo3", this.app.Country);
            this.SetRange("CustomerInfo4", this.app.NumberOfPerson);

            var range = this.GetRange("Customers");

            var customers = EZVisitCustomerAttendeeManager.SelectByCondition("IsEnabled = 1 and AppID=" + this.appId);
            int rowCount = 2;
            while (customers.Count > rowCount)
            {
                var r = this.GetRow(range.Cells[2, 1], range.Cells[2, 6]);
                r.Copy(Type.Missing);
                r.Insert(XlInsertShiftDirection.xlShiftDown, false);
                rowCount++;
            }

            int i = 1;

            foreach (EZVisitCustomerAttendeeTableEntity customer in customers)
            {
                this.SetRange(range.Cells[i, 1], customer.NameEN + "\n" + customer.NameCN);
                this.SetRange(range.Cells[i, 2], customer.CompanyEN + "\n" + customer.CompanyCN);
                this.SetRange(range.Cells[i, 3], customer.TitleEN + "\n" + customer.TitleCN);
                this.SetRange(range.Cells[i, 4], customer.ResponsibilityText);

                i++;
            }

            this.SetRange("CustomerInfo5", this.app.VisitObjective);
            this.SetRange("CustomerInfo6", this.app.RevenuePotential);

            this.SetRange("CustomerInfo7", this.app.PotentialRevenueTimeframeText);
            this.SetRange("CustomerInfo8", this.app.SalesStageText);
            this.SetRange("CustomerInfo9", this.app.IsInRFP.Value ? "YES" : "NO");
            this.SetRange("CustomerInfo10", this.app.RFPDetail);
            this.SetRange("CustomerInfo11", this.app.IsSensitiveIssue.Value ? "YES" : "NO");
            this.SetRange("CustomerInfo12", this.app.IsThereSensitiveIssue);
            this.SetRange("CustomerInfo13", this.app.IsKeyMessage.Value ? "YES" : "NO");
            this.SetRange("CustomerInfo14", this.app.IsThereKeyMessage);
            this.SetRange("CustomerInfo15", this.app.CompanyProfile);
            this.SetRange("CustomerInfo16", this.app.AccountTypeText);
        }

        private void GenerateAttendeesInfo()
        {
            var range = this.GetRange("Attendees");

            var attendees = EZVisitALAttendeeManager.SelectByCondition("IsEnabled = 1 and AppID=" + this.appId);

            int totalAttendees = attendees.Count;

            if (totalAttendees > 0)
            {
                this.SetRange("AttendeeInfo1", totalAttendees);
            }

            int rowCount = 2;
            while (totalAttendees > rowCount)
            {
                var r = this.GetRow(range.Cells[2, 1], range.Cells[2, 6]);
                r.Copy(Type.Missing);
                r.Insert(XlInsertShiftDirection.xlShiftDown, false);
                rowCount++;
            }

            int i = 1;

            foreach (EZVisitALAttendeeTableEntity attendee in attendees)
            {
                this.SetRange(range.Cells[i, 1], attendee.EmployeeNameEN);
                this.SetRange(range.Cells[i, 3], attendee.EmployeeTitle);

                i++;
            }
        }

        private void GenerateAppInfo()
        {
            this.SetRange("EZVisitID", this.app.EZVisitReqNo);
            this.SetRange("AppNo", this.app.AppNo);
            this.SetRange("CAT", this.app.CATBranch);
            this.SetRange("Account", this.app.Account);

            string requestor = string.Format("{0} ({1}) {2}", this.app.RequesterNameEN, this.app.RequesterNo, this.app.RequesterNameCN);

            this.SetRange("RequesterInfo1", requestor);
            this.SetRange("RequesterInfo2", this.app.RequesterOfficeTel);
            this.SetRange("RequesterInfo3", this.app.RequesterMobile);
            this.SetRange("RequesterInfo4", this.app.RequesterTitle);

            string contact = string.Format("{0} ({1}) {2}", this.app.SomeoneElseNameEN, this.app.SomeoneElseNo, this.app.SomeoneElseNameCN);
            this.SetRange("RequesterInfo6", contact);
            this.SetRange("RequesterInfo7", this.app.SomeoneElseTel);

            string codpp = string.Format("{0} ({1}) {2}", this.app.CODPPCheckPersonNameEN, this.app.CODPPCheckPersonNo, this.app.CODPPCheckPersonNameCN);
            this.SetRange("RequesterInfo9", codpp);
        }

        private void SetRange<T>(string range, T value)
        {
            this.excelExport.MyApp.get_Range(range, Type.Missing).Value2 = value;
        }

        private void SetRange<T>(object cell, T value)
        {
            this.excelExport.MyApp.get_Range(cell, cell).Value2 = value;
        }

        private Range GetRange(string range)
        {
            return this.excelExport.MyApp.get_Range(range, Type.Missing);
        }

        private Range GetRow(object cell1, object cell2)
        {
            return this.excelExport.MyApp.get_Range(cell1, cell2).EntireRow;
        }
    }
}